<template>
  <div style="margin-top: 10px" class="app-contain">
    <el-row :gutter="50">
      <el-col :span="14">
        <el-table v-loading="listLoading" :data="tableData" fit highlight-current-row style="width: 100%" @row-click="itemSelect">
          <el-table-column prop="shortTitle" label="题干"  show-overflow-tooltip />
          <el-table-column prop="questionType" label="题型"  :formatter="questionTypeFormatter" width="70" />
          <el-table-column prop="subjectName" label="学科"  width="50" />
          <el-table-column prop="createTime" label="做题时间"  width="170" />
        </el-table>
        <pagination v-show="total>0" :total="total" :background="false" :page.sync="queryParam.pageIndex" :limit.sync="queryParam.pageSize"
                    @pagination="search" style="margin-top: 20px"/>
      </el-col>
      <el-col  :span="10" >
        <el-card  class="record-answer-info">
          <el-form>
            <el-form-item>
              <QuestionAnswerShow :qType="selectItem.questionType" :qLoading="qAnswerLoading" :question="selectItem.questionItem"  :answer="selectItem.answerItem"/>
            </el-form-item>
          </el-form>
        </el-card>
        
        <el-card class="ai-analysis mt-20" v-loading="aiLoading">
          <el-form>
            <el-form-item>
              <el-button type="primary" @click="aiAnalyze(selectItem.questionItem.id)">AI解析</el-button>
            </el-form-item>
            <el-form-item v-if="aiAnalysis">
              <div class="analysis-section">
                <h4>选项解析：</h4>
                <div class="analysis-content">{{ aiAnalysis.analysis }}</div>
                <h4 class="mt-10">解题思路：</h4>
                <div class="analysis-content">{{ aiAnalysis.reasoning }}</div>
                <h4 class="mt-10">正确答案：</h4>
                <div class="analysis-content">{{ aiAnalysis.correct }}</div>
              </div>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { mapState, mapGetters } from 'vuex'
import Pagination from '@/components/Pagination'
import questionAnswerApi from '@/api/questionAnswer'
import QuestionAnswerShow from '../exam/components/QuestionAnswerShow'

export default {
  components: { Pagination, QuestionAnswerShow },
  data () {
    return {
      queryParam: {
        pageIndex: 1,
        pageSize: 10
      },
      listLoading: false,
      tableData: [],
      total: 0,
      qAnswerLoading: false,
      selectItem: {
        questionType: 0,
        questionItem: null,
        answerItem: null
      },
      aiLoading: false,
      aiAnalysis: null
    }
  },
  created () {
    this.search()
  },
  methods: {
    search () {
      this.listLoading = true
      this.tableData = [] // 初始化或清空之前的数据
      this.total = 0
      questionAnswerApi.pageList(this.queryParam).then(data => {
        if (data && data.response) {
          const re = data.response
          this.tableData = re.list || [] // 确保 re.list 存在，否则为空数组
          this.total = re.total || 0
          this.queryParam.pageIndex = re.pageNum || 1 // 设置默认值
          if (this.tableData.length > 0) {
            this.qAnswerShow(this.tableData[0].id)
          } else {
            // 如果列表为空，清空右侧的题目详情和AI解析
            this.selectItem = { questionType: 0, questionItem: null, answerItem: null }
            this.aiAnalysis = null
          }
        } else {
          this.$message.error('获取错题列表失败：响应数据格式不正确')
          this.tableData = []
          this.total = 0
        }
      }).catch(error => {
        console.error("获取错题列表错误:", error)
        this.$message.error('获取错题列表失败，请检查网络或联系管理员')
        this.tableData = []
        this.total = 0
      }).finally(() => {
        this.listLoading = false
      })
    },
    itemSelect (row, column, event) {
      this.qAnswerShow(row.id)
    },
    qAnswerShow(id) {
      this.id=id
      this.qAnswerLoading = true
      this.aiAnalysis = null // 切换题目时，清除旧的AI解析结果
      questionAnswerApi.select(id).then(re => {
        if (re && re.response) {
          const response = re.response
          this.selectItem.questionType = response.questionVM?.questionType
          this.selectItem.questionItem = response.questionVM
          this.selectItem.answerItem = response.questionAnswerVM
        } else {
          this.$message.error('获取题目详情失败：响应数据格式不正确')
          // 清空题目详情
          this.selectItem = { questionType: 0, questionItem: null, answerItem: null }
        }
      }).catch(error => {
        console.error("获取题目详情错误:", error)
        this.$message.error('获取题目详情失败，请稍后再试')
        this.selectItem = { questionType: 0, questionItem: null, answerItem: null }
      }).finally(() => {
        this.qAnswerLoading = false
      })
    },
    questionTypeFormatter (row, column, cellValue, index) {
      // 确保 this.enumFormat 和 this.questionTypeEnum 可用
      if (typeof this.enumFormat === 'function' && this.questionTypeEnum) {
        return this.enumFormat(this.questionTypeEnum, cellValue)
      }
      return cellValue
    },
    aiAnalyze() {
      if (!this.id) {
        this.$message.warning('请先选择一道题目，再进行AI解析。');
        return;
      }
      this.aiLoading = true
      this.aiAnalysis = null // 清除旧的解析结果
      questionAnswerApi.aiAnalysis(this.id).then(re => {
        if (re && re.response) {
          this.aiAnalysis = re.response
        } else {
          this.$message.error('AI解析失败：响应数据格式不正确')
        }
      }).catch(error => {
        console.error("AI解析错误:", error)
        this.$message.error('AI解析失败，请稍后再试')
      }).finally(() => {
        this.aiLoading = false
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.mt-20 {
  margin-top: 20px;
}
.analysis-section {
  line-height: 1.6;
  h4 {
    color: #409eff;
    margin: 10px 0;
  }
  .analysis-content {
    background: #f5f7fa;
    padding: 10px;
    border-radius: 4px;
  }
}
</style>
